package com.lingyun.ucm.web.mvc.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lingyun.ucm.web.mvc.service.ConfigAcquireFailLogService;
import com.lingyun.ucm.web.mvc.service.impl.ConfigAcquireFailLogServiceImpl;

/**
 * 
 * @author Terrence2013
 * 2018年1月24日 上午9:50:40
 * 异步向浏览器推送配置获取失败数量消息
 */
public class ConfigAcquireFailMsgPushServlet extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = 1294190096098205554L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AsyncContext asyncContext = request.startAsync();
        asyncContext.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent asyncEvent) throws IOException {
                asyncEvent.getSuppliedResponse().getWriter().close();
            }
            @Override
            public void onTimeout(AsyncEvent asyncEvent) throws IOException {
            }
            @Override
            public void onError(AsyncEvent asyncEvent) throws IOException {
            }
            @Override
            public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
            }
        });
        new Thread(new FailMsgThread(asyncContext)).start();
    }
    
    private class FailMsgThread implements Runnable {
        private ConfigAcquireFailLogService configAcquireFailLogService = new ConfigAcquireFailLogServiceImpl();
        private AsyncContext asyncContext;

        public FailMsgThread(AsyncContext asyncContext) {
            this.asyncContext = asyncContext;
        }

        @Override
        public void run() {
            try {
                ServletResponse response = asyncContext.getResponse();
                Thread.sleep(1000*10);
                PrintWriter out = response.getWriter();
                int num = configAcquireFailLogService.countFailLog();
                out.write(num == 0 ? '0' : num);
                out.flush();
                asyncContext.complete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
